package com.zyh.controller;

import com.zyh.entity.User;
import com.zyh.service.UserService;
import com.zyh.util.MailUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ModelAndView mav;

    @RequestMapping("selectUserByUsernameAndPasswordMvc")
    public ModelAndView selectUserByUsernameAndPasswordMvc(HttpSession httpSession, @Param("email") String email, @Param("password") String password){
        User user = userService.selectByEmailAndPassword(email, password);
        String safeCode = (String)httpSession.getAttribute("checkCode");
        if(user!=null){
            httpSession.setAttribute("user",user);
            mav.setViewName("/book/selectAll.do");
        }else{
            mav.setViewName("redirect:/user/login_form.jsp");
        }
        return mav;
    }
    @RequestMapping("insertMvc")
    public ModelAndView insertMvc(User user,String number,HttpSession session){
        String checkCode =(String) session.getAttribute("checkCode");
        if(number.equals(checkCode)==true){
            userService.insert(user);
            mav.setViewName("redirect:/user/verify_form.jsp");
            MailUtil.sendSimpleMail(user.getEmail(),"邮箱激活","<a href = 'http://localhost:8989/Mid_term_project_dang_220317_war_exploded/user/updateState.do?userId="+user.getId()+"'>点击激活</a>");
        }else{
            mav.setViewName("/user/register_form.jsp");
        }
        return mav;
    }

    @RequestMapping("removeOut")
    public ModelAndView removeOut(HttpSession session){
        session.removeAttribute("user");
        mav.setViewName("redirect:/book/selectAll.do");
        return mav;
    }

    @RequestMapping("/updateState")
    public ModelAndView updateState(Integer userId,HttpSession session){
        userService.updateState(userId);
        User user = userService.selectByUserId(userId);
        session.setAttribute("user",user);
        mav.setViewName("/user/register_ok.jsp");
        return mav;
    }
}
